package com.usdt.common.config;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 代码拷贝自oss sdk
 * <p>
 * 作用是还原 ossClient.generatePresignedUrl() 方法对key的处理方式
 */
public class OssSdkUtils {
    /**
     * oss sdk 编码queryString的代码
     * 拷贝自 com.aliyun.oss.common.utils.HttpUtil
     *
     * @param value
     * @param encoding
     * @return
     */
    public static String urlEncode(String value, String encoding) {
        if (value == null) {
            return "";
        }

        try {
            String encoded = URLEncoder.encode(value, encoding);
            return encoded.replace("+", "%20").replace("*", "%2A")
                    .replace("~", "%7E").replace("/", "%2F");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static String urlEncodeKey(String key, String encoding) {
        StringBuffer resultUri = new StringBuffer();

        String[] keys = key.split("/");
        resultUri.append(urlEncode(keys[0], encoding));
        for (int i = 1; i < keys.length; i++) {
            resultUri.append("/").append(urlEncode(keys[i], encoding));
        }

        if (key.endsWith("/")) {
            // String#split ignores trailing empty strings,
            // e.g., "a/b/" will be split as a 2-entries array,
            // so we have to append all the trailing slash to the uri.
            for (int i = key.length() - 1; i >= 0; i--) {
                if (key.charAt(i) == '/') {
                    resultUri.append("/");
                } else {
                    break;
                }
            }
        }

        return resultUri.toString();
    }

    /**
     * Encode request parameters to URL segment.
     */
    public static String paramToQueryString(Map<String, String> params, String charset) {

        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder paramString = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> p : params.entrySet()) {
            String key = p.getKey();
            String value = p.getValue();

            if (!first) {
                paramString.append("&");
            }

            // Urlencode each request parameter
            paramString.append(urlEncode(key, charset));
            if (value != null) {
                paramString.append("=").append(urlEncode(value, charset));
            }

            first = false;
        }

        return paramString.toString();
    }

}
